<template>
  <div class="dashboard-container">
    <!-- 数据概览区域 -->
    <div class="data-overview">
      <div class="stat-card">
        <div class="stat-title">总品牌数</div>
        <div class="stat-value">{{ totalBrands }}</div>
        <div class="stat-desc">有效品牌数量</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">总分类数</div>
        <div class="stat-value">{{ totalCategories }}</div>
        <div class="stat-desc">有效分类数量</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">总商品数</div>
        <div class="stat-value">{{ totalProducts }}</div>
        <div class="stat-desc">品牌与分类合计</div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 品牌数量饼图容器 -->
      <div class="chart-item">
        <h3 class="chart-title">品牌数量统计</h3>
        <div ref="brandChartRef" class="chart-wrapper"></div>
      </div>

      <!-- 分类数量饼图容器 -->
      <div class="chart-item">
        <h3 class="chart-title">分类数量统计</h3>
        <div ref="categoryChartRef" class="chart-wrapper"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import productAPI from '../api/product_api.js'

export default {
  name: 'ProductCharts',
  setup() {
    // 图表容器引用
    const brandChartRef = ref(null)
    const categoryChartRef = ref(null)

    // 图表实例存储
    let brandChart = null
    let categoryChart = null

    // 数据变量
    const brandData = ref([])
    const categoryData = ref([])

    // 计算总数据
    const totalBrands = computed(() => {
      return brandData.value.length
    })

    const totalCategories = computed(() => {
      return categoryData.value.length
    })

    const totalProducts = computed(() => {
      const brandSum = brandData.value.reduce((sum, item) => sum + item.value, 0)
      const categorySum = categoryData.value.reduce((sum, item) => sum + item.value, 0)
      return brandSum + categorySum
    })

    /**
     * 初始化图表的通用方法
     */
    const initCommonChart = (container, data, title) => {
      if (!container) return null

      // 销毁已有实例
      const existingChart = echarts.getInstanceByDom(container)
      if (existingChart) {
        existingChart.dispose()
      }

      // 初始化新实例
      const chart = echarts.init(container)

      // 图表配置
      const option = {
        title: {
          text: title,
          subtext: '数量分布详情',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}件 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          formatter: (name) => {
            const item = data.find(item => item.name === name)
            return item?.value > 0 ? name : ''
          },
          type: 'scroll',
          top: 30
        },
        series: [
          {
            name: '数量',
            type: 'pie',
            radius: '50%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: (params) => params.data.value > 0,
              formatter: '{b}: {c}件'
            },
            labelLine: {
              show: (params) => params.data.value > 0
            }
          }
        ]
      }

      chart.setOption(option)
      return chart
    }

    // 加载品牌数据
    const loadBrandData = async () => {
      try {
        console.log('开始请求品牌数据...')
        const response = await productAPI.cbrand()
        console.log('品牌数据原始响应:', response)

        brandData.value = (response || []).map(item => ({
          name: item.name || '未知品牌',
          value: Number(item.nums) || 0
        })).filter(item => item.value > 0)

        brandChart = initCommonChart(brandChartRef.value, brandData.value, '品牌数量统计')
      } catch (error) {
        console.error('获取品牌数据失败:', error.message)
        brandChart = initCommonChart(brandChartRef.value, brandData.value, '品牌数量统计')
      }
    }

    // 加载分类数据
    const loadCategoryData = async () => {
      try {
        console.log('开始请求分类数据...')
        const response = await productAPI.ccategory()
        console.log('分类数据原始响应:', response)

        categoryData.value = (response || []).map(item => ({
          name: item.name || '未知分类',
          value: Number(item.nums) || 0
        })).filter(item => item.value > 0)

        categoryChart = initCommonChart(categoryChartRef.value, categoryData.value, '分类数量统计')
      } catch (error) {
        console.error('获取分类数据失败:', error.message)
        categoryChart = initCommonChart(categoryChartRef.value, categoryData.value, '分类数量统计')
      }
    }

    // 处理窗口大小变化
    const handleResize = () => {
      if (brandChart) brandChart.resize()
      if (categoryChart) categoryChart.resize()
    }

    // 组件生命周期
    onMounted(() => {
      loadBrandData()
      loadCategoryData()
      window.addEventListener('resize', handleResize)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      if (brandChart) brandChart.dispose()
      if (categoryChart) categoryChart.dispose()
      brandChart = null
      categoryChart = null
    })

    return {
      brandChartRef,
      categoryChartRef,
      totalBrands,
      totalCategories,
      totalProducts
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  box-sizing: border-box;
}

/* 数据概览样式 */
.data-overview {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.stat-value {
  color: #333;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-desc {
  color: #999;
  font-size: 12px;
}

/* 图表区域样式 */
.charts-container {
  width: 100%;
  min-height: 600px;
  display: flex;
  gap: 20px;
  box-sizing: border-box;
}

.chart-item {
  flex: 1;
  min-width: 300px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.chart-title {
  text-align: center;
  margin-bottom: 15px;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.chart-wrapper {
  width: 100%;
  height: 500px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .charts-container {
    flex-direction: column;
  }
  .chart-wrapper {
    height: 400px;
  }
  .data-overview {
    flex-direction: column;
  }
  .stat-card {
    min-width: auto;
  }
}
</style>